<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="申请时间" prop="applicationTime">
        <el-date-picker
          clearable
          v-model="queryParams.applicationTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择申请时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="申请人" prop="applicat">
        <el-input
          v-model="queryParams.applicat"
          placeholder="请输入申请人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- 新增类型搜索下拉框 -->
      <el-form-item label="类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择类型"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="item in shenqingtype"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['le:pendingTasks:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['le:pendingTasks:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['le:pendingTasks:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['le:pendingTasks:export']"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="FileAdd"
          @click="handleOpenApplyDialog"
          class="apply-btn"
          >发起申请</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="pendingTasksList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="业务id" align="center" prop="bussniessId" />
      <!-- <el-table-column label="task编号" align="center" prop="taskId" /> -->
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <!-- 直接查找匹配的label -->
          {{
            shenqingtype.find(
              (item) => String(item.value) === String(scope.row.type)
            )?.label || ""
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="assignee" />
      <!-- <el-table-column label="操作人id" align="center" prop="assigneeId" /> -->
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.status === 1
                ? 'info'
                : scope.row.status === 2
                ? 'success'
                : 'danger'
            "
            size="small"
          >
            {{
              scope.row.status === 1
                ? "申请中"
                : scope.row.status === 2
                ? "已完成"
                : "已关闭"
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="申请时间"
        align="center"
        prop="applicationTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.applicationTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applicat" />
      <!-- 修改申请人id列显示 -->
      <!-- <el-table-column label="申请人id" align="center" prop="applicatId">
        <template #default="scope">
          {{ getUserNickName(scope.row.applicatId) }}
          <span v-if="!getUserNickName(scope.row.applicatId)"
            >({{ scope.row.applicatId }})</span
          >
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        label="完成时间"
        align="center"
        prop="finishTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.finishTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="处理状态" align="center" prop="isHandle">
        <template #default="scope">
          <el-tag
            :type="scope.row.isHandle === 1 ? 'success' : 'danger'"
            size="small"
          >
            {{ scope.row.isHandle === 1 ? "已处理" : "未处理" }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column label="审核步骤" align="center" prop="stepNo" /> -->
      <!-- <el-table-column label="额外字段1" align="center" prop="extraField1" /> -->
      <!-- <el-table-column label="额外字段2" align="center" prop="extraField2" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="toStep(scope.row)"
            v-hasPermi="['le:pendingTasks:edit']"
            :disabled="scope.row.status === 2 && scope.row.isHandle === 1"
            >处理</el-button
          >
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['le:pendingTasks:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['le:pendingTasks:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改待办任务对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="pendingTasksRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="业务id" prop="bussniessId">
          <el-input v-model="form.bussniessId" placeholder="请输入业务id" />
        </el-form-item>
        <el-form-item label="task编号" prop="taskId">
          <el-input v-model="form.taskId" placeholder="请输入task编号" />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="操作人" prop="assignee">
          <el-input v-model="form.assignee" placeholder="请输入操作人" />
        </el-form-item>
        <el-form-item label="操作人id" prop="assigneeId">
          <el-input v-model="form.assigneeId" placeholder="请输入操作人id" />
        </el-form-item>
        <el-form-item label="申请时间" prop="applicationTime">
          <el-date-picker
            clearable
            v-model="form.applicationTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择申请时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="申请人" prop="applicat">
          <el-input v-model="form.applicat" placeholder="请输入申请人" />
        </el-form-item>
        <el-form-item label="申请人id" prop="applicatId">
          <el-input v-model="form.applicatId" placeholder="请输入申请人id" />
        </el-form-item>
        <el-form-item label="完成时间" prop="finishTime">
          <el-date-picker
            clearable
            v-model="form.finishTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择完成时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否处理完成" prop="isHandle">
          <el-input v-model="form.isHandle" placeholder="请输入是否处理完成" />
        </el-form-item>
        <el-form-item label="审核步骤" prop="stepNo">
          <el-input v-model="form.stepNo" placeholder="请输入审核步骤" />
        </el-form-item>
        <el-form-item label="额外字段1" prop="extraField1">
          <el-input v-model="form.extraField1" placeholder="请输入额外字段1" />
        </el-form-item>
        <el-form-item label="额外字段2" prop="extraField2">
          <el-input v-model="form.extraField2" placeholder="请输入额外字段2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增【发起申请】弹窗 -->
    <el-dialog
      title="选择申请单据类别"
      v-model="openApplyDialog"
      width="300px"
      append-to-body
    >
      <div class="apply-dialog-content">
        <p class="type-title">单据类别:</p>
        <!-- 申请类型选择按钮 -->
        <div class="type-btn-group">
          <el-button
            type="default"
            :class="{ 'selected-type': selectedApplyType === 'ruzhu' }"
            @click="selectedApplyType = 'ruzhu'"
            >入住</el-button
          >
          <el-button
            type="default"
            :class="{ 'selected-type': selectedApplyType === 'tuizhu' }"
            @click="selectedApplyType = 'tuizhu'"
            >退住</el-button
          >
          <el-button
            type="default"
            :class="{ 'selected-type': selectedApplyType === 'leave' }"
            @click="selectedApplyType = 'leave'"
            >请假</el-button
          >
        </div>
      </div>
      <!-- 弹窗底部按钮 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleApplyCancel">取消</el-button>
          <el-button type="primary" @click="handleApplyConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PendingTasks">
import {
  listPendingTasks,
  getPendingTasks,
  delPendingTasks,
  addPendingTasks,
  updatePendingTasks,
} from "@/api/le/pendingTasks";
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { getRequest } from "@/api/le/request";
import { getElderlyByElderlyId } from "@/api/le/elderly";
import { getUser, listUser } from "@/api/system/user";
import { useUserStore } from '@/store/modules/user'
// 使用
const userStore = useUserStore()

const router = useRouter();
const { proxy } = getCurrentInstance();
const { shenqingtype } = proxy.useDict("shenqingtype");

// 新增【发起申请】相关响应式数据
const openApplyDialog = ref(false); // 控制弹窗显示/隐藏
const selectedApplyType = ref(""); // 存储选中的申请类型（ruzhu/tuizhu/leave）
// 2. 定义 formatTime 函数（与其他页面保持一致，避免未定义错误）
const formatTime = (time) => {
  if (!time) return "";
  const date = new Date(time);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hour = String(date.getHours()).padStart(2, "0");
  const minute = String(date.getMinutes()).padStart(2, "0");
  const second = String(date.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
};
const pendingTasksList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    bussniessId: null,
    taskId: null,
    title: null,
    type: null,
    assignee: null,
    assigneeId: null,
    status: null,
    applicationTime: null,
    applicat: null,
    applicatId: null,
    finishTime: null,
    isHandle: null,
    stepNo: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);
//去处理
const toStep = async (pt) => {
  console.log(pt);
  const taskType = pt.type;
  console.log(taskType);

  // 2. 入住类型：跳转到step3审批页面
  if (taskType === 3) {
    router.push({
      path: "/le/ruzhuxq/processEntry",
      query: {
        step: 3,
        pendingTaskId: pt.id,
        taskType: 3
      }
    });
  }
  // 3. 退住类型：暂设为空操作
  else if (taskType === 1) {
    // console.log("pt:",pt);
    const ptStr = JSON.stringify(pt);
    // console.log("json的pt:",ptStr);
    // ElMessage.info("退住类型处理功能暂未实现");
     router.push({ path: "/xietong/shenqing/tui/le/tuizhu",
      query: { ptStr :ptStr } });
    // 后期补充退住跳转逻辑：router.push(...)
  } else if (taskType === 2) {
    try {
      // 1. 获取请假业务ID（关联 leave_request.id）
      const bussniessId = pt.bussniessId;
      console.log(bussniessId);
      if (!bussniessId || isNaN(bussniessId)) {
        ElMessage.error("无效的请假业务ID，无法处理");
        return;
      }
      // 2. 步骤1：查请假详情（leave_request 表）→ 拿到 elderlyId（老人外键）
      const leaveRes = await getRequest(bussniessId);
      console.log(leaveRes);
      if (leaveRes.code !== 200 || !leaveRes.data) {
        ElMessage.error("查询请假详情失败，请重试");
        return;
      }
      const leaveData = leaveRes.data;
      console.log(leaveData);
      const elderlyId = leaveData.elderlyId; // 从请假表拿老人ID
      if (!elderlyId) {
        ElMessage.error("请假信息中无老人ID，无法查询老人信息");
        return;
      }

      // 3. 步骤2：调用新接口，按 elderlyId 查老人完整信息（核心修复！）
      const elderRes = await getElderlyByElderlyId(elderlyId);
      console.log(elderRes);
      if (elderRes.code !== 200 || !elderRes.data) {
        ElMessage.warning("未查询到老人信息，将显示默认值");
        var elderInfo = {
          elderlyName: "未知老人",
          elderlyIdCard: "无",
          elderlyPhone: "无",
          nursingLevel: "无",
          floorName: "",
          roomNo: "",
          bedNo: "",
          caregiverName: "无",
        };
      } else {
        elderInfo = elderRes.data; // 从新接口拿到完整老人信息
      }

      // 4. 步骤3：查护理员昵称（申请人信息）
      let nurseNickName = "护理员A";
      if (leaveData.creator) {
        const nurseRes = await getUser(leaveData.creator);
        console.log(nurseRes);
        if (nurseRes.code === 200) {
          nurseNickName = nurseRes.data.nickName;
          console.log(nurseNickName);
        }
      }

      // 5. 构造 basicForm（从新接口的 elderInfo 取值，字段完全匹配）
      const basicForm = {
        elderlyId: elderlyId || "",
        elderName: elderInfo.elderlyName || "未知老人", // 老人姓名（新接口字段）
        idCard: elderInfo.elderlyIdCard || "无", // 身份证号（新接口字段）
        phone: elderInfo.elderlyPhone || "无", // 联系电话（新接口字段）
        nursingLevel: elderInfo.nursingLevel || "无", // 护理等级（新接口字段）
        bed:
          `${elderInfo.floorName || ""}楼${elderInfo.roomNo || ""}房间${
            elderInfo.bedNo || ""
          }床位` || "无", // 床位（新接口字段）
        nurse: elderInfo.caregiverName || "无", // 护理员（新接口字段）
      };

      // 6. 构造 applyForm（从请假表取值，不变）
      const applyForm = {
        accompanyType: leaveData.companionType || "无",
        accompanyName:
          leaveData.companionName === "0"
            ? "无"
            : leaveData.companionName || "无",
        accompanyPhone:
          leaveData.companionPhone === "0"
            ? "无"
            : leaveData.companionPhone || "无",
        leavePeriod: [leaveData.leaveStartTime, leaveData.expectedEndTime],
        leaveDays: leaveData.expectedLeaveDays || 0,
        leaveReason: leaveData.leaveReason || "无",
      };

      // 7. 构造 submitData（携带护理员昵称，不变）
      const submitData = {
        elderlyId: elderlyId || "",
        businessId: leaveData.id || bussniessId,
        nurseNickName: nurseNickName, // 申请人（护理员昵称）
        createTime: leaveData.createTime || formatTime(new Date()),
        leaveStartTime: leaveData.leaveStartTime || "",
        expectedEndTime: leaveData.expectedEndTime || "",
      };

      // 8. 跳转 index1，传递完整参数
      router.push({
        path: "/leaveApplication/secondStep",
        query: {
          elderlyId: basicForm.elderlyId,
          billNo: bussniessId,
          basicForm: JSON.stringify(basicForm), // 含完整老人信息
          applyForm: JSON.stringify(applyForm),
          submitData: JSON.stringify(submitData), // 含护理员昵称
          title: pt.title,
          ptId: pt.id, // 添加待办任务ID参数
        },
      });
    } catch (err) {
      console.error("处理请假任务异常：", err);
      if (err.response?.status) {
        ElMessage.error(`接口调用失败（状态码：${err.response.status}）`);
      }
    }
  }
};

/** 查询待办任务列表 */
function getList() {
  loading.value = true;
  console.log("代办查询人",userStore.id);
  
  queryParams.value.assigneeId = userStore.id;
  listPendingTasks(queryParams.value).then((response) => {
    pendingTasksList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    bussniessId: null,
    taskId: null,
    title: null,
    type: null,
    assignee: null,
    assigneeId: null,
    status: null,
    applicationTime: null,
    applicat: null,
    applicatId: null,
    finishTime: null,
    isHandle: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    stepNo: null,
    extraField1: null,
    extraField2: null,
  };
  proxy.resetForm("pendingTasksRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加待办任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getPendingTasks(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改待办任务";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["pendingTasksRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updatePendingTasks(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPendingTasks(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除待办任务编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPendingTasks(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "le/pendingTasks/export",
    {
      ...queryParams.value,
    },
    `pendingTasks_${new Date().getTime()}.xlsx`
  );
}
// 新增【发起申请】弹窗方法
// 1. 打开弹窗
const handleOpenApplyDialog = () => {
  selectedApplyType.value = ""; // 重置选中状态
  openApplyDialog.value = true;
};

// 2. 取消弹窗
const handleApplyCancel = () => {
  openApplyDialog.value = false;
  selectedApplyType.value = "";
};

// 3. 确定选择并跳转对应页面
const handleApplyConfirm = () => {
  if (!selectedApplyType.value) {
    ElMessage.warning("请选择申请单据类别");
    return;
  }
  // 根据选中类型匹配路由地址
  const routeMap = {
    ruzhu: "/le/ruzhuxq/processEntry", // 入住地址
    tuizhu: "/xietong/shenqing/tui/le/tuizhu", // 退住地址
    leave: "/xietong/shenqing/leaveApplication", // 请假地址
  };
  // 跳转路由
  router.push(routeMap[selectedApplyType.value]);
  // 关闭弹窗并重置
  openApplyDialog.value = false;
  selectedApplyType.value = "";
};

getList();
</script>
<style scoped>
.apply-dialog-content {
  padding: 10px 0;
}
.type-title {
  margin-bottom: 15px;
  font-size: 14px;
  font-weight: 500;
}
.type-btn-group {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-bottom: 10px;
}
/* 选中类型按钮高亮样式 */
.selected-type {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}
</style>
